package org.example.domain.strategy.service.rule.RuleFilter.LogicFilterImp;

import lombok.extern.slf4j.Slf4j;
import org.example.domain.strategy.model.Raffle.FilterMatterEntity;
import org.example.domain.strategy.model.Raffle.RuleActionEntity;
import org.example.domain.strategy.model.Raffle.StrategyRuleEntity;
import org.example.domain.strategy.model.valobj.RuleLogicCheckTypeVO;
import org.example.domain.strategy.repository.IStrategyRepository;
import org.example.domain.strategy.service.rule.RuleFilter.ILogicFilter;
import org.example.domain.strategy.service.annotation.LogicStrategy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
@Slf4j
@LogicStrategy(logicModel = RuleActionEntity.LogicModel.RULE_LOCK)
public class RuleLockLogicFilter implements ILogicFilter {

    @Autowired
    private IStrategyRepository strategyRepository;

    private int userAmount = 0;

    @Override
    public RuleActionEntity<RuleActionEntity.RaffleBeforeEntity> doBeforeFilter(FilterMatterEntity filterMatterEntity) {
        return null;
    }

    @Override
    public RuleActionEntity<RuleActionEntity.RaffleBetweenEntity> doBetweenFilter(FilterMatterEntity filterMatterEntity) {

        String awardId = filterMatterEntity.getAwardId();
        String strategyId = filterMatterEntity.getStrategyId();
        String ruleModel = filterMatterEntity.getRuleModel();

        // 查询规则值配置；当前奖品ID，抽奖中规则对应的校验值。如；1、2、6
        StrategyRuleEntity strategyRuleEntity = strategyRepository.queryStrategyRuleEntityByStrategyIdAndRuleModelAndAwardId(strategyId,ruleModel,awardId);
        Long ruleValue = Long.valueOf(strategyRuleEntity.getRuleValue());

        // 用户抽奖次数大于规则限定值，规则放行
        if (ruleValue <= userAmount){
            log.info("用户抽奖次数大于规则限定值，规则放行");
            return RuleActionEntity.<RuleActionEntity.RaffleBetweenEntity>builder()
                    .codeAllowOrTakeOver(RuleLogicCheckTypeVO.ALLOW.getCode())
                    .ruleModel(strategyRuleEntity.getRuleModel())
                    .build();
        }


        // 用户抽奖次数小于规则限定值，规则拦截
        log.info("用户抽奖次数小于规则限定值，规则拦截");
        return  RuleActionEntity.<RuleActionEntity.RaffleBetweenEntity>builder()
                .codeAllowOrTakeOver(RuleLogicCheckTypeVO.TAKE_OVER.getCode())
                .ruleModel(strategyRuleEntity.getRuleModel())
                .build();
    }
}
